<?php
/**
 * FastApp.
 * 9/21/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Game\Api\Service;

use App\Fastapp\Api\Service\BaseService;
use App\Fastapp\Model\AccountWalletLog;
use App\Game\Model\GameAccountVip;
use App\Game\Model\GameVip;

class VipService extends BaseService
{
    public function list(): array
    {
        $list = GameVip::query()->orderByDesc('level')->get();
        $amount = $level = 0;
        try {
            $res = $this->level();
            $amount = $res['amount'];
            $level = $res['level'];
        } catch (\Throwable) {
        }
        return ['list' => $list, 'amount' => $amount, 'level' => $level];
    }

    public function level(int $uid = 0): array
    {
        $uid = $uid ?: get_uid();
        $currency_id = get_user_cache('currency_id', $uid);
        $vip = GameAccountVip::query()->firstOrCreate(['user_id' => $uid]);
        $level = (int)$vip->level;
        $query = AccountWalletLog::query()->where([
            'user_id' => $uid,
            'currency_id' => $currency_id,
            'type' => AccountWalletLog::USE_BALANCE,
            'object_type' => AccountWalletLog::OBJ_TYPE_GAME_BAT
        ]);
        $lem = GameVip::query()->where('level', '<', $level + 1)->sum('amount');
        $amount = bcsub((string)$query->sum('amount'), (string)$lem, 2);
        $next = GameVip::query()->where('level', '>', $level)->orderBy('level')->first();
        return ['amount' => $amount, 'level' => $level, 'next' => $next];
    }
}